import { Shortcut_Name_Enum } from "@enum/app.enum";
import { Ipc_ChannelEnum } from "@enum/channel.enum";
import { Ipc } from "@main/helper/ipcMain";
import { globalShortcut } from "electron";


export interface ShortcutRegistType {
    name:Shortcut_Name_Enum;
    callBack:()=>void;
}

//注册全局快捷键
export class Shortcut {

    private static _instance: Shortcut;

    static factory(): Shortcut {
        if (!this._instance) this._instance = new this();
        return this._instance;
    }

    private _data : Array<ShortcutRegistType> = [];

    constructor(){}

    private _set(params:ShortcutRegistType) :void{
        this._data.push(params)
    }
    private _del(name:Shortcut_Name_Enum) :void{
        this._data.filter(shortcut => shortcut.name !== name)
    }

    regist(params:ShortcutRegistType) :void{

        //这里选择如果重复则不走逻辑，因为这里的callback都是ipc 覆盖没用意义
       if(this._data.findIndex(shortcut => shortcut.name === params.name) === -1){
            globalShortcut.register(params.name,params.callBack);
            this._set(params)
       }
       
    }
    
    unRegist(name:Shortcut_Name_Enum) :void{

        globalShortcut.unregister(name);
        this._del(name)

    }


}

export class ShortcutService {

    static shortcutInstance = new Shortcut()

    static regist():void{

        Ipc.on<[Shortcut_Name_Enum]>(Ipc_ChannelEnum.APP_REGIST_SHORTCUT,(_,name)=>{

            this.shortcutInstance.regist({
                name,
                callBack:()=>{
                    Ipc.send({
                        key:Ipc_ChannelEnum.APP_SEND_SHORTCUT,
                        params:{}
                    })
                }
            })
         })
    }

    static unRegist():void{
        
        Ipc.on<[Shortcut_Name_Enum]>(Ipc_ChannelEnum.APP_UN_REGIST_SHORTCUT,(_,name)=>{

           this.shortcutInstance.unRegist(name)
        })
    }
    
    static on():void {
        this.regist()
        this.unRegist()
    }
}
